/**
 * Copyright (C) DXHM 版权所有
 * @文件名 HttpPostUtils.java
 * @包名 com.dx.util
 * @说明 TODO(描述文件做什么)
 * @作者 王少泽
 * @时间 2014-8-21 下午5:26:59
 * @版本 V1.0
 */
package com.lf.cloud.grab.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
 * @类名 HttpPostUtils
 * @描述 TODO(用途说明)
 * @作者	刘飞
 * @日期 2014-8-21 下午5:26:59 ========修改日志=======
 * 
 */
public class HttpPostUtils {
	
	
	/**
	 * @名称 uploadFile
	 * @描述 上传要件
	 * @作者	刘飞
	 * @时间 2014-8-21 下午9:44:49
	 * @param uploadURL
	 * @param inputName
	 * @param fname
	 * @param uploadFileName
	 * @return  1 上传失败 2 上传成功 3 文件类型错误 4文件超过2M
	 * @throws Exception
	 */
	public static String uploadFile(String uploadURL,String inputName,String fname,String uploadFileName) throws Exception {

		try {

			String sufix=fname.substring(fname.lastIndexOf(".")+1);
			String BOUNDARY = "---------bsbsbsbsbs"; // 定义数据分隔线
			URL url = new URL(uploadURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Accept",
					"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			conn.setRequestProperty(
					"User-Agent",
					"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
			conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
			conn.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setRequestProperty("Cache-Control", "max-age=0");
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			File file = new File(fname);
			StringBuilder sb = new StringBuilder();
			sb.append("--");
			sb.append(BOUNDARY);
			sb.append("\r\n");
			sb.append("Content-Disposition: form-data;name="+inputName
					+ ";filename=" + (null==uploadFileName? file.getName():uploadFileName) + "\r\n");
			sb.append("Content-Type:" +getContentType(sufix)+"\r\n\r\n");
			byte[] data = sb.toString().getBytes();
			out.write(data);
			DataInputStream in = new DataInputStream(new FileInputStream(file));
			try {
				int bytes = 0;
				byte[] bufferOut = new byte[1024];
				while ((bytes = in.read(bufferOut)) != -1) {
					out.write(bufferOut, 0, bytes);
				}
				out.write("\r\n".getBytes());
			} catch (Exception e) {
				throw e;
			} finally {
				in.close();
			}
			out.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes());
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			StringBuffer ret= new StringBuffer();
			String line=null;
			while ((line = reader.readLine()) != null) {
				ret.append(line);
			}
			return ret.toString();
		} catch (Exception e) {
			throw e;
		} finally {
		}
	}
	
	/* '.xls','.doc','.txt','.png','.jpeg','.jpg','.gif'*/
	public static final String getContentType(String sufix){
		String t = contentTypeMap.get(sufix);
		if(null==t){
			return "application/octet-stream";
		}else return t;
	}
	final static ConcurrentHashMap<String, String> contentTypeMap=new ConcurrentHashMap<String, String>();
	static{
		contentTypeMap.put("xls", "application/msexcel");
		contentTypeMap.put("pdf", "application/pdf");
		contentTypeMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		contentTypeMap.put("doc", "application/msword");
		contentTypeMap.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
		contentTypeMap.put("txt", "text/plain");
		contentTypeMap.put("png", "image/png");
		contentTypeMap.put("jpeg", "image/jpeg");
		contentTypeMap.put("jpg", "image/jpg");
		contentTypeMap.put("gif", "image/gif");
	}
	
	
	
	 /** 
     * 发送HttpPost请求 
     *  
     * @param strURL 
     *            服务地址 
     * @param params 
     *            json字符串 
     * @return 成功:返回json字符串<br/> 
     */  
    public static byte[] dealPost(String strURL, String params) {  
        System.out.println("====>请求地址:"+strURL);  
        System.out.println("====>请求参数:"+params);  
       String result ="ERROR";
       byte[] data = null;
        try {  
            URL url = new URL(strURL);// 创建连接  
            HttpURLConnection connection = (HttpURLConnection) url  
                    .openConnection();  
            connection.setDoOutput(true);  
            connection.setDoInput(true);  
            connection.setUseCaches(false);  
            connection.setInstanceFollowRedirects(true);  
            connection.setRequestMethod("POST"); // 设置请求方式  
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
            connection.connect();  
            OutputStreamWriter out = new OutputStreamWriter(  
                    connection.getOutputStream(), "UTF-8"); // utf-8编码  
            if(params!=null && params!=""){
            	
            	out.append(params);  
            }
            out.flush();  
            out.close();  
            // 读取响应  
            int length = (int) connection.getContentLength();// 获取长度  
            
            
            
            InputStream is = connection.getInputStream();  
            if (length != -1) {  
                data = new byte[length];  
                byte[] temp = new byte[1024*1024];  
                int readLen = 0;  
                int destPos = 0;  
                while ((readLen = is.read(temp)) > 0) {  
                    System.arraycopy(temp, 0, data, destPos, readLen);  
                    destPos += readLen;  
                }  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
            result = "ERROR";
        }  finally{
        }
        return data; // 自定义错误信息  
    }  
    public static byte[] getImgByte(String strURL) {  

		
    	System.out.println("====>请求地址："+strURL);
    	
    	ByteArrayOutputStream output = new ByteArrayOutputStream();
    	GetMethod postMethod = null;
		
		try {
			// 创建httpClient实体
			HttpClient httpClient = new HttpClient();
			httpClient.getParams().setSoTimeout(1000*60);
			// 设置编码
			httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			// 设置请求url
			postMethod = new GetMethod(strURL);
			// 设置参数
			//postMethod.setRequestBody(parmList.toArray(new NameValuePair[parmList.size()]));
			// 发送http请求
			int statusCode = httpClient.executeMethod(postMethod);// http响应状态
			
			//InputStream responseBodyAsStream  = new Inp

			if (statusCode == HttpStatus.SC_OK) {
				// 读取返回数据
						InputStream is = postMethod.getResponseBodyAsStream();
						
						byte[] buffer = new byte[4096];
					    int n = 0;
					    while (-1 != (n = is.read(buffer))) {
					        output.write(buffer, 0, n);
					    }
					   // byte[] byteArray = output.toByteArray();
					    return output.toByteArray();
			} else {
				throw new RuntimeException("http请求失败");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (postMethod != null) {
				postMethod.releaseConnection();// 释放连接
			}
		}
    }  

    public static String sendHttpRequestToString(String url, Map<String, String> httpParmMap) {
		String result = "";

		List<NameValuePair> parmList = new ArrayList<NameValuePair>();
		for (Entry<String, String> entry : httpParmMap.entrySet()) {
			parmList.add(new NameValuePair(entry.getKey(), entry.getValue()));
		}

		PostMethod postMethod = null;
		try {
			// 创建httpClient实体
			HttpClient httpClient = new HttpClient();
			httpClient.getParams().setSoTimeout(1000*60);
			// 设置编码
			httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			// 设置请求url
			//postMethod = new PostMethod(url);
			postMethod = new PostMethod(url);
			// 设置参数
			postMethod.setRequestBody(parmList.toArray(new NameValuePair[parmList.size()]));
			// 发送http请求
			int statusCode = httpClient.executeMethod(postMethod);// http响应状态
			
			//InputStream responseBodyAsStream  = new Inp

			if (statusCode == HttpStatus.SC_OK) {
				// 读取返回数据
				result = postMethod.getResponseBodyAsString();
			} else {
				throw new RuntimeException("http请求失败");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (postMethod != null) {
				postMethod.releaseConnection();// 释放连接
			}
		}
		return result;
	}
    
    
    public static String doPost(String url, String json) {
		String result = "";


		PostMethod postMethod = null;
		try {
			// 创建httpClient实体
			HttpClient httpClient = new HttpClient();
			httpClient.getParams().setSoTimeout(1000*60);
			// 设置编码
			httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			
			httpClient.getHostConfiguration().getParams().setParameter("Content-type","application/json; charset=utf-8");
			httpClient.getHostConfiguration().getParams().setParameter("Accept", "application/json");
			
			// 设置请求url
			//postMethod = new PostMethod(url);
			postMethod = new PostMethod(url);
			// 设置参数
			postMethod.setRequestBody(json);
			
			
			
			// 发送http请求
			int statusCode = httpClient.executeMethod(postMethod);// http响应状态
			
			//InputStream responseBodyAsStream  = new Inp
			System.out.println(statusCode);
			if (statusCode == HttpStatus.SC_OK) {
				// 读取返回数据
				result = postMethod.getResponseBodyAsString();
			} else {
				
				throw new RuntimeException("http请求失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (postMethod != null) {
				postMethod.releaseConnection();// 释放连接
			}
		}
		return result;
	}
    
    
    
    public static String doGet(String url, Map<String, String> httpParmMap) {
    	String result = "";
    	
    	
    	url += "?";
    	boolean flag = true;
    	for (Entry<String, String> entry : httpParmMap.entrySet()) {
    		url += entry.getKey()+"="+entry.getValue()+"&";
    	}
    	
    	url = url.substring(0,url.length()-1);
    	
    	System.out.println(url);
    	
    	GetMethod postMethod = null;
    	try {
    		// 创建httpClient实体
    		HttpClient httpClient = new HttpClient();
    		httpClient.getParams().setSoTimeout(1000*60);
    		// 设置编码
    		httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    		// 设置请求url
    		//postMethod = new PostMethod(url);
    		
    		postMethod = new GetMethod(url);
    		// 设置参数
    		//postMethod.setParams(httpParmMap);
    		
    		
    		
    		
    		// 发送http请求
    		int statusCode = httpClient.executeMethod(postMethod);// http响应状态
    		
    		//InputStream responseBodyAsStream  = new Inp
    		
    		if (statusCode == HttpStatus.SC_OK) {
    			// 读取返回数据
    			result = postMethod.getResponseBodyAsString();
    		} else {
    			throw new RuntimeException("http请求失败");
    		}
    	} catch (Exception e) {
    		throw new RuntimeException(e);
    	} finally {
    		if (postMethod != null) {
    			postMethod.releaseConnection();// 释放连接
    		}
    	}
    	return result;
    }
    
    
    
    
    
    
	public static void main(String[] args) throws Exception {
		String fname = "F:\\testupload.byjava21.txt";
		File f=new File(fname);
		System.err.println(f.getPath());
		System.err.println(f.getName());
//		String ret = uploadFile("http://49.4.168.9/upload?name=2000008","myfile",fname);
//		System.out.println(ret);
	}
}
